package com.fx.usercenter.interceptions;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @Program: redis_cookie
 * @ClassName LoginInterceptor
 * @Description: 用户登录拦截器，校验session，身份验证
 * @Version 1.0
 **/
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截到请求："+request.getRequestURI());
        System.out.println("当前令牌："+request.getSession().getId());
        String s = request.getSession().getId();
        System.out.println("登录状态："+redisTemplate.hasKey(s));
        if (redisTemplate.hasKey(s)) {//延长登录状态
            redisTemplate.expire(s, 30, TimeUnit.MINUTES);//设置过期时间，30分钟
            return true;
        }else {//身份过期
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write("身份过期，非法请求");
            return false;
        }
    }
}
